import { GameSceneView } from '../base/ViewSet';
import { $, cNodePool, cSound, cStorage, cUI, gameData, pfApi } from '../../config/Config';
import Utils from '../../common/utils/Utils';
import {
    event_resume_game,
} from '../../config/ClientEvent';
import bullet from '../../items/bullets/bullet';
import { LQCollideSystem } from '../../../lq_collide_system/lq_collide_system';
import PlayerCtrl from '../../player/PlayerCtrl';
import EnemyBase from '../../items/enemys/EnemyBase';
import GameUi from '../../ctrls/GameUi';
import EnemyRootCtrl from '../../ctrls/EnemyRootCtrl';
import PropRootCtrl from '../../ctrls/PropRootCtrl';
import enemy_bullet from '../../items/bullets/enemy_bullet';
import EnemyBulletBoom from '../../items/pars/EnemyBulletBoom';
import BossHpRoot from '../uiItems/BossHpRoot';

export var gameScene: GameScene;

const { ccclass, property } = cc._decorator;
@ccclass
export default class GameScene extends GameSceneView {
    @property({ displayName: "Ui节点", tooltip: "Ui节点", type: GameUi })
    GameUI: GameUi = null;
    @property({ displayName: "敌人根节点", tooltip: "敌人根节点", type: EnemyRootCtrl })
    EnemyRoot: EnemyRootCtrl = null;
    @property({ displayName: "掉落物品根节点", tooltip: "掉落物品根节点", type: PropRootCtrl })
    PropRoot: PropRootCtrl = null;
    @property({ displayName: "BOSS血条", tooltip: "BOSS血条", type: BossHpRoot })
    bossHpRoot: BossHpRoot = null;
    // @property({ displayName: "角色节点", tooltip: "角色节点", type: PlayerCtrl })
    heroCtrl: PlayerCtrl = null;
    @property(cc.Node)
    skillRootNode: cc.Node = undefined;
    @property(cc.Node)
    maskNode: cc.Node = undefined;
    @property(cc.Node)
    bgKuang: cc.Node = undefined;
    time: number = 0;
    /*暂停*/
    is_pause: boolean = false;
    gameTimer: number = -1;

    colorIndex: number = 0;
    colorArr: cc.Color[] = [new cc.Color(0, 255, 0), new cc.Color(255, 175, 173), new cc.Color(255, 102, 51), new cc.Color(230, 0, 255), new cc.Color(0, 0, 255), new cc.Color(255, 0, 0)];

    protected onLoad(): void {
        this.heroCtrl = this.node.getChildByName("player").getComponent(PlayerCtrl);
        this.skillRootNode = this.node.getChildByName("skillRootNode");
        gameScene = this;
        LQCollideSystem.is_enable = true;
        cSound.playMusic($.Sound.game_bgm, 0.5);
        this.bossHpRoot.node.active = false;
    }

    updateBuKuang() {
        gameData.updatePlayerData();
        this.bgKuang.stopAllActions();
        cc.tween(this.bgKuang)
            .to(9, { color: this.colorArr[this.colorIndex] })
            .start();
        // this.bgKuang.color = this.colorArr[this.colorIndex];
        this.colorIndex++;
        if (this.colorIndex >= this.colorArr.length) this.colorIndex = 0;
    }

    /**/
    start() {
        pfApi.startRecordVideo(90);
        this.gameTimer = setInterval(this.gameTimerFunc.bind(this), 100);
        this.updateBuKuang();
        // this.EnemyRoot.addBoss();
    }

    initScene() {
        gameData.initData();
    }

    gameTimerFunc() {
        if (this.is_pause) return;
        if (gameData._game_milliscoend % 2500 == 0 && gameData._game_scoend < gameData._pre_wave_start_time + gameData._pre_wave_enemy_time) {
            this.EnemyRoot.addEnemy();
        }
        gameData._game_milliscoend += 100;
        gameData._game_scoend += 0.1;
        gameData._kill_enemy_time -= 100;
        if (gameData._kill_enemy_time % 1000 == 0) {
            this.GameUI.updateTimeLabel();
            if (this.EnemyRoot.node.childrenCount > 0) if (gameData._kill_enemy_time == 0) {
                cUI.showTips("TIME  OVER!");
                this.gameResult();
            }
        }

        this.heroCtrl.skill_ctrl.judgeSkillList();

        // console.log('------------gameData._game_scoend:', gameData._game_scoend);
    }

    /**
     * 发射子弹
     * @param dir 
     * @param playerPos 
     */
    shootBullet(dir: cc.Vec2, playerPos: cc.Vec2) {
       
        cNodePool.get($.Prefab.yuan_bullet).then(value => {
            value.position = cc.v2(playerPos.x + 45 * dir.x * this.heroCtrl._volume, playerPos.y + 45 * dir.y * this.heroCtrl._volume);
            value.parent = this.node;
            value.getComponent(bullet).shootToPos(cc.v2(playerPos.x + this.heroCtrl._shoot_range * dir.x, playerPos.y + this.heroCtrl._shoot_range * dir.y), this.heroCtrl._bullet_speed);
        })
    }

    /**
     * 敌人发射子弹
     * @param dir 
     * @param enemyPos 
     */
     enemyShootBullet(enemyPos: cc.Vec2, speed: number) {
        let vector:cc.Vec2 = cc.v2(this.heroCtrl.node.x - enemyPos.x, this.heroCtrl.node.y - enemyPos.y);
        let dir = vector.normalize();
        cNodePool.get($.Prefab.enemy_bullet).then(value => {
            value.position = cc.v2(enemyPos.x, enemyPos.y);
            value.parent = this.node;
            value.getComponent(enemy_bullet).shootToPos(cc.v2(enemyPos.x + 1000 * dir.x, enemyPos.y + 1000 * dir.y), 10/this.heroCtrl._speed);
        })
    }

    /**
     * boss 发射子弹
     * @param endPos 
     * @param startPos 
     */
    bossShootBullet(endPos: cc.Vec2, startPos: cc.Vec2){
        cNodePool.get($.Prefab.enemy_bullet).then(value => {
            value.position = startPos;
            value.parent = this.node;
            value.getComponent(enemy_bullet).shootToPos(endPos, 8/this.heroCtrl._speed);
        })
    }

    /**
     * 敌人子弹击中爆碎效果  enemyBulletBoom
     * @param position 
     */
    addEnemyShootBoom(position: cc.Vec2){
        cSound.playEffect($.Sound["jizhong" + 3]);
        cNodePool.get($.Prefab.enemyBulletBoom).then(value => {
            value.parent = this.node;
            value.getComponent(EnemyBulletBoom).initState(undefined, position);
        })
    }

    startGame() {
        console.log('------------开始游戏');
    }

    protected initEvents() {
        super.initEvents();
    }

    onDestroy(): void {
        super.onDestroy();
        cUI.removeAllLayer();
        cSound.pauseMusic();
        clearInterval(this.gameTimer);

        gameData.updatePlayerData();
    }


    // 可以通过下面的代码来创建一个纯色贴图
    // let texture = new cc.RenderTexture();
    // texture.initWithData(new Uint8Array([0, 0, 0]), cc.Texture2D.PixelFormat.RGB888, 1, 1);

    /*暂停游戏*/
    pauseGame() {
        this.is_pause = true;
        this.node.pauseAllActions();
        this.node.children.forEach(value => {
            value.pauseAllActions();
        })
    }
    
    /*恢复游戏*/
    resumeGame() {
        this.is_pause = false;
        this.node.resumeAllActions();
        event_resume_game.emit();
        this.maskNode.active = false;
        this.node.children.forEach(value => {
            value.resumeAllActions();
        })
    }

    pass() {
        this.pauseGame();
    }

    /*游戏结算*/
    gameResult() {
        this.is_pause = true;
        cUI.addLayer($.Prefab.gameResult);
        this.unscheduleAllCallbacks();
    }

    gameRevival(){
        this.is_pause = true;
        cUI.addLayer($.Prefab.rerivalNode);
        this.unscheduleAllCallbacks();
    }

    onBtnPause(e?: cc.Event.EventTouch) {
        cSound.playEffect($.Sound.btn_0);
        cUI.addLayer($.Prefab.pause);
        this.pauseGame();
    }

    startCheckEnemyCount(){
        if (gameData._game_scoend < gameData._pre_wave_start_time + gameData._pre_wave_enemy_time) this.EnemyRoot.addEnemy();
        this.unschedule(this.checkEnemyCount);
        this.scheduleOnce(this.checkEnemyCount, 1.5);
        this.GameUI.updateEnemy();

    }

    checkEnemyCount(){
        this.EnemyRoot.checkEnemyCount();
    }
}